<template>
  <div class="login-container">
    <!--上半部分-->
    <div class="top" ref="scrollContainer" @scroll="handleScroll">
      <div class="newSession">
        <el-tooltip content="新会话" placement="bottom" effect="light" :open-delay="1000">
          <el-button size="small" round icon="el-icon-plus" @click="newSession">新会话</el-button>
        </el-tooltip>
      </div>
      <div class="toBottom" v-show="showScrollButton">
        <el-tooltip content="回到底部" placement="top" effect="light" :open-delay="1000">
          <el-button size="mini" icon="el-icon-bottom" circle @click="scrollToBottom"></el-button>
        </el-tooltip>
      </div>
      <!--顶部提示-->
      <div class="tips">
        <div style="display: flex">
          <img src="../../assets/images/a.png" alt="">
          <p>
            <strong>{{ fullText }}</strong>
          </p>
        </div>
        <div class="cardBody" @click="selectText(item)" v-for="item in textList" :key="item">✨ {{ item }}</div>
      </div>
      <div class="sendAndQuestion" v-for="(item,index) in isSend" :key="index">
        <div class="send">
          <p>{{ item.send }}</p>
        </div>
        <div class="question">
          <img src="../../assets/images/a.png" alt="">
          <div class="content">
            <div class="common" v-html="item.question" ref="lastQuestion"></div>
            <div class="knowledge"  v-if="item.knowledge.length > 0">
              <div class="bottom" style="text-align: left">
                以上内容由 AI生成，请仔细甄别 <br>
                <span>针对您的提问，e宝问答小助手提供以下出处，供您参考。</span>
              </div>
              <div v-for="(k,ki) in item.knowledge" :key="ki" ref="knowledgeList">
                <div>
                  <span class="title" @click="toFile(k.url)">{{ ki + 1 }}. {{ k.title }}</span>
                  <span class="title2">{{ k.subtitle }}</span>
                </div>
                <p class="titCont">{{ k.content }}</p>
              </div>
            </div>
            <div class="webSearch" v-if="item.webSearch && item.webSearch.length>0">
              <div class="bottom" style="text-align: left">
                <span>针对您的提问，e宝问答小助手在网上整理了一下资料，供您参考。</span>
              </div>
              <div v-for="(w,wi) in item.webSearch" :key="wi" ref="knowledgeList">
                <p class="title" ref="webSearchList" @click="toFile2(w.url)" style="font-weight: 600;font-size: 2vh">
                  {{ wi+1 }}. {{w.title}}
                </p>
                <!--<p style="font-size: 2vh;color: #666;line-height: 1.2em">{{w.content}}</p>-->
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!--下半部分-->
    <div class="bto">
      <!--按钮组-->
      <div class="btnGroup">
        <div>
          <el-button icon="el-icon-menu" :type="select1" round @click="isSelect1('101')">国家标准</el-button>
        </div>
        <div>
          <el-button icon="el-icon-menu" :type="select2" round @click="isSelect2('102')">行业标准</el-button>
        </div>
        <div>
          <el-button icon="el-icon-menu" :type="select3" round @click="isSelect3('103')">地方标准</el-button>
        </div>
      </div>
      <!--输入框-->
      <div class="inputMK">
        <el-input
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 8}"
            placeholder=""
            resize="none"
            v-model="textarea2"
            @input="changeText"
        >
        </el-input>
        <div class="bottonBtn">
          <!--<el-button class="btn1" :type="model" round size="mini" icon="el-icon-s-help" @click="deepThink">深度思考</el-button>-->
          <el-button class="btn1" :type="model" round size="mini" icon="el-icon-s-help" @click="deepThink">联网搜索
          </el-button>
          <el-button size="small" type="primary" :icon="btnIcon" circle @click="sendQuestion"
                     :disabled="toSend"></el-button>
        </div>
      </div>
      <!--提示-->
      <div class="bottom">内容由 AI生成，请仔细甄别</div>
    </div>
  </div>
</template>

<script>
//后台方法
import {chatapi, posturl} from '@/api/chat';
//获取到字符转转换成markdown格式
import MarkdownIt from 'markdown-it';

export default {
  data() {
    return {
      //按钮组状态
      select1: 'primary',
      s1: true,
      select2: '',
      s2: false,
      select3: '',
      s3: false,
      //深度思考按钮状态
      model: '',
      m1: false,
      //标准先择参数
      params1: {
        p1: '101',
        p2: '',
        p3: '',
      },
      //提问的问题
      textarea2: '',
      //发送的问题和收到的回答
      isSend: [],
      //顶部提示
      fullText: "您好！我是一局发展的e宝问答小助手，可以为您查询施工规范相关资料，您可以试着这样问我：",
      //页面上展示可选择的问题
      textList:[
        '落地脚手架有几种分类形式？',
        '基坑支护施工的要点有哪些？',
        '混凝土梁的模板什么时候需要对拉螺杆？',
        '基坑开挖前，需要符合哪些规定？',
      ],
      //判断是都展示置底按钮
      showScrollButton:false,
      // 定义显示按钮的阈值（距离底部多少像素时显示）
      scrollThreshold: 500,
      //定时器
      typingInterval: null,
      //按钮图标
      btnIcon: "el-icon-top",
      //发送按钮能否点击
      toSend:true
    };
  },
  mounted() {
    let sendChatApi = localStorage.getItem('sendChatApi')

    if (sendChatApi) {
      this.isSend = JSON.parse(sendChatApi)
      this.$nextTick(() => {
        this.scrollToBottom()
      })
    } else {
      this.isSend = []
    }
  },
  methods: {
    //知识库对应的文件跳转
    toFile(url) {
      let baseUrl = 'http://chatgpt-test.tbchip.com'
      let phone = '&phone=18810815351'
      let api = `${baseUrl}/${url}${phone}`
      posturl({url:api}).then(res => {
        if (res.code === 200) {
          window.open(res.msg)
        }
      })
    },
    //联网搜索对应的跳转
    toFile2(url) {
      window.open(url)
    },
    //标准按钮组选择
    isSelect1(v) {
      if (this.s1) {
        this.select1 = ''
        this.s1 = false
        this.params1.p1 = ''
      } else {
        this.select1 = 'primary'
        this.s1 = true
        this.params1.p1 = v
      }
    },
    isSelect2(v) {
      if (this.s2) {
        this.select2 = ''
        this.s2 = false
        this.params1.p2 = ''
      } else {
        this.select2 = 'primary'
        this.s2 = true
        this.params1.p2 = v
      }
    },
    isSelect3(v) {
      if (this.s3) {
        this.select3 = ''
        this.s3 = false
        this.params1.p3 = ''
      } else {
        this.select3 = 'primary'
        this.s3 = true
        this.params1.p3 = v
      }
    },
    //联网搜索按钮选择
    deepThink() {
      if (this.m1) {
        this.model = ''
        this.m1 = false
      } else {
        this.model = 'primary'
        this.m1 = true
      }
    },
    //调用接口进行数据交互（打字机效果+逐条渲染）
    chatApi() {
      const md = new MarkdownIt();
      let list = []
      if (this.s1) {
        list.push('101')
      }
      if (this.s2) {
        list.push('102')
      }
      if (this.s3) {
        list.push('103')
      }
      let newS = this.textarea2
      this.textarea2 = ''
      chatapi({problem: newS, webSearch: this.m1 ? '1' : '0', number: JSON.stringify(list)}).then(res => {
        if (res.code === 200) {
          this.btnIcon = "el-icon-video-pause"
          this.toSend = false
          //调用打字机方法
          this.startTyping(md.render(res.data.text)).then(() => {
            // 调用逐条渲染方法
            this.startKnowledgeing(JSON.parse(res.data.knowledgeSource)).then(()=>{
              if(res.data.webSearchSource && res.data.webSearchSource.length>0){
                this.startWebSearching(JSON.parse(res.data.webSearchSource)).then(()=>{
                  this.$nextTick(() => {
                    this.btnIcon = "el-icon-top"
                    localStorage.setItem('sendChatApi', JSON.stringify(this.isSend))
                    this.scrollToBottom()
                  })
                })
              }else{
                this.btnIcon = "el-icon-top"
                localStorage.setItem('sendChatApi', JSON.stringify(this.isSend))
                this.scrollToBottom()
                this.isSend[this.isSend.length - 1].webSearch = null
              }
            })
          })
        }
      })
    },
    //监听输入框变化
    changeText(){
      this.toSend = this.textarea2 === '';
    },
    //发送问题方法
    sendQuestion() {
      if(this.typingInterval){
        this.btnIcon = "el-icon-top"
        this.toSend = true
        clearInterval(this.typingInterval)
        this.typingInterval = null
      }else{
        let obj = {
          send: this.textarea2,
          question: '搜索中',
          knowledge: [],
          webSearch: []
        }
        this.isSend.push(obj)
        this.toSend = true
        this.btnIcon = "el-icon-loading"
        this.$nextTick(() => {
          this.scrollToBottom()
        })
        this.chatApi()
      }
    },
    //点击页面上对应问题方法
    selectText(v) {
      this.textarea2 = v
      this.toSend = false
      this.textarea = false
    },
    //滚动条置底方法
    scrollToBottom() {
      const container = this.$refs.scrollContainer
      container.scrollTo({
        top: container.scrollHeight,
        behavior: 'smooth'
      })
    },
    //监听滚动调位置，到某个位置时可执行 置底
    handleScroll() {
      const container = this.$refs.scrollContainer
      // 计算距离底部的距离
      const distanceToBottom = container.scrollHeight - container.scrollTop - container.clientHeight
      // 如果距离底部大于阈值，显示按钮，否则隐藏
      this.showScrollButton = distanceToBottom > this.scrollThreshold
    },
    //新绘画方法
    newSession(){
      localStorage.removeItem('sendChatApi')
      this.isSend = []
    },
    //打字机开始方法
    startTyping(text) {
      return new Promise((resolve, reject) => {
        try {
          this.stopTyping();

          let charIndex = 0;
          let currentText = '';

          this.typingInterval = setInterval(() => {
            if (charIndex < text.length) {
              currentText += text.charAt(charIndex);
              charIndex++;
              this.isSend[this.isSend.length - 1].question = currentText;
              this.scrollToBottom()
            } else {
              this.stopTyping();
              resolve(true); // 传递完成状态
            }
          }, 10);
        } catch (error) {
          this.stopTyping();
          reject(error);
        }
      });
    },
    //逐条渲染方法
    startKnowledgeing(data) {
      return new Promise((resolve, reject) => {
        try {
          this.stopTyping();
          let dataIndex = 0;
          this.typingInterval = setInterval(() => {
            if (dataIndex < data.length) {
              let item = data[dataIndex];
              dataIndex++;
              this.isSend[this.isSend.length - 1].knowledge.push(item);
              this.scrollToBottom()
            } else {
              this.stopTyping();
              resolve(true); // 传递完成状态
            }
          }, 500);
        } catch (error) {
          this.stopTyping();
          reject(error);
        }
      });
    },
    startWebSearching(data) {
      return new Promise((resolve, reject) => {
        try {
          this.stopTyping();
          let dataIndex = 0;
          this.typingInterval = setInterval(() => {
            if (dataIndex < data.length) {
              let item = data[dataIndex];
              dataIndex++;
              this.isSend[this.isSend.length - 1].webSearch.push(item);
              this.scrollToBottom()
            } else {
              this.stopTyping();
              resolve(true); // 传递完成状态
            }
          }, 500);
        } catch (error) {
          this.stopTyping();
          reject(error);
        }
      });
    },
    //清空定时器
    stopTyping() {
      if (this.typingInterval) {
        clearInterval(this.typingInterval)
        this.typingInterval = null
      }
    },
  },
  beforeDestroy() {
    localStorage.removeItem('sendChatApi')
  }

};
</script>

<style>
p {
  margin: 10px 0;
}
</style>
<style lang="scss" scoped>
.login-container {
  line-height: 1.2em;
  width: 100%;
  box-sizing: border-box;
  height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: space-between;

  .top {
    height: 75vh;
    overflow-y: scroll;
    .newSession {
      background: #fff;
      z-index: 9;
      position: fixed;
      width: 100%;
      padding: 1vh 2vh 1vh 7vh;
      box-shadow: 0 0 3px 3px rgba(100,100,100,0.1);
      ::v-deep .el-button--small.is-round{
        background: #e6f4ff;
        box-shadow: 0 0 3px 3px rgba(100,100,100,0.1);
      }
    }

    .toBottom {
      position: fixed;
      bottom: 22vh;
      right: 2vh;
    }

    .sendAndQuestion {
      .send {
        text-align: right;
        padding-right: 1vh;

        p {
          max-width: 60%;
          text-align: left;
          display: inline-block;
          background: #fff;
          font-size: 2vh;
          padding: 1.54vh 2vh;
          border-radius: 2vh;
        }
      }

      .question {
        display: flex;

        img {
          width: 4.2vh;
          height: 5.2vh;
          margin-left: 1vh;
        }

        .content {
          line-height: 1.5em;
          margin-left: 2vh;
          padding: 1vh 1.2vh;
          background: #e6f4ff;
          border-radius: 2vh;
          max-width: 93%;

          .common {
            font-size: 1.8vh;
            line-height: 1.5em;
            padding-left: 1vh;
            color: #666;
            border-left: 2px solid #99a9bf;
          }

          .knowledge, .webSearch {
            .title {
              display: inline-block;
              margin: .6vh;
              font-weight: 600;
              font-size: 2.2vh;
              cursor: pointer;
              color: #5d9fff;
              text-decoration: underline;
            }
            .title2{
              font-weight: 600;
              font-size: 2vh;
              margin-left: 1vh;
              color: #111
            }
            .titCont{
              font-size: 2vh;
              color: #111;
            }
          }
        }
      }
    }

    // 滚动条样式
    &::-webkit-scrollbar {
      width: 4px;
    }

    &::-webkit-scrollbar-track {
      -webkit-box-shadow: rgba(0, 0, 0, 0.3);
      border-radius: 4px;
    }

    &::-webkit-scrollbar-thumb {
      border-radius: 4px;
      background: rgba(0, 0, 0, 0.2);
      -webkit-box-shadow: rgba(0, 0, 0, 0.5);
    }

    &::-webkit-scrollbar-thumb:window-inactive {
      background: rgba(0, 0, 0, 0.4);
    }
  }

  .bto {
    height: 23vh;
    display: flex;
    flex-direction: column;
    justify-content: flex-end
  }

  .tips {
    box-sizing: border-box;
    padding-top: 7vh;

    img {
      width: 4.2vh;
      height: 5.2vh;
      margin: 1vh 0 0 1vh;
    }

    p {
      margin-left: 2vh;
    }

    .cardBody {
      padding: 1.5vh;
      border: 1px solid #e7e7e7;
      border-radius: 1vh;
      width: 60%;
      margin-top: 1vh;
      margin-left: 7vh;
      font-size: 2vh;

      &:hover {
        box-shadow: 0 0 5px 5px rgba(125, 125, 125, 0.1);
      }
    }
  }

  .btnGroup {
    display: flex;
    justify-content: center;

    div {
      margin: 0 .5vh;

      ::v-deep .el-button.is-round {
        padding: 1.4vh 2.8vh;
      }
    }
  }

  .inputMK {
    text-align: center;
    margin: 2px 2.5%;
    border-radius: 2vh;
    border: 1px solid #e7e7e7;

    ::v-deep .el-textarea__inner {
      border-radius: 2vh;
      border: none;
    }

    .bottonBtn {
      padding: 1vh;
      display: flex;
      justify-content: space-between;

      ::v-deep .el-button.is-round {
        padding: .3vh 1.2vh;
      }
    }
  }

  .bottom {
    text-align: center;
    color: #909399;
    font-size: 1.6vh;
    margin-top: 6px;
  }

  ::v-deep .el-form-item__label {
    color: #fff !important;
  }

  // 滚动条样式
  ::-webkit-scrollbar {
    width: 10px;
  }

  ::-webkit-scrollbar-track {
    -webkit-box-shadow: rgba(0, 0, 0, 0.3);
    border-radius: 8px;
  }

  ::-webkit-scrollbar-thumb {
    border-radius: 10px;
    background: rgba(0, 0, 0, 0.2);
    -webkit-box-shadow: rgba(0, 0, 0, 0.5);
  }

  ::-webkit-scrollbar-thumb:window-inactive {
    background: rgba(0, 0, 0, 0.4);
  }

  //设置更改input 默认颜色
  ::-webkit-input-placeholder {
    /* WebKit browsers */
    color: #bebebe;
    font-size: 16px;
  }

  ::-moz-placeholder {
    /* Mozilla Firefox 19+ */
    color: #bebebe;
    font-size: 16px;
  }

  :-ms-input-placeholder {
    /* Internet Explorer 10+ */
    color: #bebebe;
    font-size: 16px;
  }

  input:-webkit-autofill {
    box-shadow: 0 0 0 1000px rgba(255, 255, 255, 1) inset;
    -webkit-box-shadow: 0 0 0 1000px rgba(255, 255, 255, 1) inset;
    -webkit-text-fill-color: #2c2e33;
  }
}

@media (max-width: 767px) {
  .btnGroup {
    div {
      ::v-deep .el-button.is-round {
        padding: 1vh 1.2vh !important;
      }

      ::v-deep .el-button {
        font-size: 1.4vh;
      }
    }
  }
  .top {
    height: 80vh !important;
    .sendAndQuestion {
      .send {
        padding-right: 0 !important;
        p {
          font-size: 1.5vh !important;
          max-width: 76% !important;
        }
      }
      .question {
        img{
          width: 3.2vh !important;
          height: 4.2vh !important;
          margin-left: 1vh !important;
        }
        .content {
          margin-left: 1vh !important;
          max-width: 85% !important;
          .common {
            font-size: 1.6vh !important;
          }
          .knowledge, .webSearch {
            .title {
              font-size: 1.7vh !important;
            }
            .title2{
              font-size: 1.7vh !important;
              margin-left: 0.2vh !important;
            }
            .titCont{
              font-size: 1.6vh !important;
            }
          }
        }
      }
    }
  }
  .bto {
    height: 19vh !important;
  }
  .toBottom{
    right: 0.5vh !important;
  }
  .newSession{
    padding: 1vh 2vh !important;
    ::v-deep .el-button--small.is-round{
      padding: 1vh 1.8vh;
      span{
        display: none;
      }
    }
  }
  .tips {
    .cardBody {
      width: 79% !important;
      font-size: 1.5vh !important;
      margin-left: 5vh !important;
    }
    img{
      width: 3.2vh !important;
      height: 4.2vh !important;
      margin-left: 1vh !important;
    }
    p{
      margin-left: 1vh !important;
    }
  }
}
</style>
